package com.ricchieri.dao;

import java.io.Serializable;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.dao.interf.IGenericDao;
import com.ricchieri.filter.BasicFilter;
import com.ricchieri.util.StringUtils;

public abstract class GenericDao implements IGenericDao, Serializable {

	private static final long serialVersionUID = 8911895448742621242L;
	
	private SessionFactory sessionFactory;

	/* (non-Javadoc)
	 * @see com.ricchieri.dao.IGenericDao#getSessionFactory()
	 */
	@Override
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/* (non-Javadoc)
	 * @see com.ricchieri.dao.IGenericDao#setSessionFactory(org.hibernate.SessionFactory)
	 */
	@Override
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/* (non-Javadoc)
	 * @see com.ricchieri.dao.IGenericDao#add(java.lang.Object)
	 */
	@Override
	public void add(Object object) {
		getSessionFactory().getCurrentSession().save(object);
	}

	/* (non-Javadoc)
	 * @see com.ricchieri.dao.IGenericDao#delete(java.lang.Object)
	 */
	@Override
	public void delete(Object object) {
		getSessionFactory().getCurrentSession().delete(object);
	}

	/* (non-Javadoc)
	 * @see com.ricchieri.dao.IGenericDao#update(java.lang.Object)
	 */
	@Override
	public void update(Object object) {
		getSessionFactory().getCurrentSession().update(object);
	}
	
	@SuppressWarnings("rawtypes")
	protected Criteria criteriaAllBasic(BasicFilter filter, Class clazz) {
		Criteria criteria = this.criteriaAllBasicWithoutOrder(filter, clazz);
		
		if(!StringUtils.isEmpty(filter.getSortField())) {
			addOrder(filter, getTableName().concat(".").concat(filter.getSortField()), criteria);
		}
		
		return criteria;
	}

	protected void addOrder(BasicFilter filter, String field, Criteria criteria) {
		if(filter.getSortOrder().equals(BusinessSettings.SORT_ASCENDING)) {
			criteria.addOrder(Order.asc(field));
		} else {
			criteria.addOrder(Order.desc(field));
		}
	}	
	
	
	@SuppressWarnings("rawtypes")
	protected Criteria criteriaAllBasicWithoutOrder(BasicFilter filter, Class clazz) {
		Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(clazz, getTableName());
		if(filter.getId() > 0){
			criteria.add(Restrictions.eq(getTableName().concat(".id"), filter.getId()));
		}
		
		if(!filter.getFindActiveInactive()) {
			criteria.add(Restrictions.eq(getTableName().concat(".active"), filter.getActive()));
		}
		
		return criteria;
	}	
	
	protected abstract String getTableName();
}
